<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>商品管理</el-breadcrumb-item>
            <el-breadcrumb-item>参数列表</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 卡片区域 -->
        <el-card>
            <el-alert title="注意:只允许为第三级分类设置相关参数" show-icon type="warning" :closable="false">
            </el-alert>
            <el-row class="selectGoods">
                <el-col>
                    <span>选择商品分类:</span>
                    <el-cascader expandTrigger="hover"
                    v-model="selectedIdArr"
                    :options="CateList"
                    :props="CateListprops"
                     @change="CateListChange" >
                     </el-cascader>
                </el-col>  
            </el-row>
             <!-- v-model 绑定的是被选中的标签页的ID -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 动态参数 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled="isButDisplay" @click="manyOnlyDialog=true">添加参数</el-button>
                    <!-- 动态参数表格 -->
                    <el-table :data="manyTableData" border stripe>
                        <el-table-column type="expand">
                            <template slot-scope="scope">
                                <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i"  closable @close="handleClose(i, scope.row)">
                                    {{item}}
                                </el-tag>
                                <el-input
                                class="input-new-tag"
                                v-if="scope.row.inputVisible"
                                v-model="scope.row.inputValue"
                                ref="saveTagInput"
                                size="small"
                                @keyup.enter.native="handleInputConfirm"
                                @blur="handleInputConfirm(scope.row)">
                                </el-input>
                                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称">
                        </el-table-column>
                        <!-- 操作 -->
                        <el-table-column  label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini" @click="removeParams(scope.row.attr_id)">删除</el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 静态属性 -->
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled="isButDisplay" @click="manyOnlyDialog=true">添加属性</el-button>
                    <!-- 静态参数表格 -->
                    <el-table :data="onlyTableData" border stripe >
                        <el-table-column type="expand"></el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column prop="attr_name" label="参数名称">
                        </el-table-column>
                        <!-- 操作 -->
                        <el-table-column  label="操作">
                            <template slot-scope="scope">
                                <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.attr_id)">编辑</el-button>
                                <el-button type="danger" icon="el-icon-delete" size="mini"  @click="removeParams(scope.row.attr_id)">删除</el-button>
                             </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>

        <!-- 添加静态属性、动态参数对话框区域 -->
        <el-dialog :title="'添加'+titleText" :visible.sync="manyOnlyDialog" @close="addDialogClose">
            <el-form ref="addRef" :model="addform" label-width="80px" :rules="addRules">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="addform.attr_name" ></el-input>
                </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="manyOnlyDialog = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
        </el-dialog>

        <!-- 编辑参数对话框 -->
        <el-dialog :title="'修改'+titleText" :visible.sync="editmanyOnlyDialog" @close="editDialogClose">
            <el-form ref="editRef" :model="editform" label-width="80px" :rules="editRules">
                <el-form-item :label="titleText" prop="attr_name">
                    <el-input v-model="editform.attr_name" ></el-input>
                </el-form-item>
            </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editmanyOnlyDialog = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
    data () {
        return {
            CateList:[],
            // 级联选择器配置数据
            CateListprops:{
                label:'cat_name',
                value:'cat_id',
                children:'children'
            },
            // 被选择的商品分类的id
            selectedIdArr:[],
            // Tabs 标签页 默认选中的那一列
            activeName:'many',
            // 动态参数数据
            manyTableData:[],
            // 静态属性参数
            onlyTableData:[],
            // 控制添加参数对话框
            manyOnlyDialog:false,
            // 添加参数表单数据
            addform:{
                attr_name:''
            },
            // 添加参数表单验证规则
            addRules:{
                attr_name: { required: true, message: '请输入参数', trigger: 'blur' }
            },
            // 编辑参数对话框
            editmanyOnlyDialog:false,
            // 编辑参数表单数据
            editform:{
                 attr_name:''
            },
            // 编辑参数表单验证规则
            editRules:{
                attr_name: { required: true, message: '请输入参数', trigger: 'blur' }
            },
        }
    },
    created(){
        this.getCateList()
    },
   methods:{
    //    渲染商品分类数据列表
      async getCateList(){
      const {data:res}= await this.$http.get('categories')
      if(res.meta.status!==200){return this.$message.error('获取商品列表失败')}
      this.CateList=res.data
    //   console.log(res.data);

    },
    // 级联选择器发生变化时调用
    CateListChange(){
        this.getParamsData()
    },
    // tab 被选中时触发
    handleTabClick(){
        this.getParamsData()
    },
    // 封装的获取动静态参数
    async getParamsData(){
        if(this.selectedIdArr.length!==3){
            this.selectedIdArr=[]
            this.manyTableData = []
            this.onlyTableData = []
            return 
        }
        // 根据选中的三级分类获取动态、静态参数
        const {data:res}= await this.$http.get(`categories/${this.cateID}/attributes`,{params:{sel:this.activeName}})
      if(res.meta.status !== 200){return this.$message.error('获取参数列表失败')}
        // 如果点了动态参数TAB栏
     if(this.activeName==='many'){
          this.manyTableData=res.data
      }else{
          this.onlyTableData=res.data
      }
    //   把attr_vals的值改成数组
        // console.log(res.data);
        res.data.forEach(item=>{
        item.attr_vals= item.attr_vals?item.attr_vals.split(' '):[]
        item.inputVisible=false
        item.inputValue =""
        // console.log(res.data);
        })
    },
    // 关闭添加参数对话框调用 重置表单
    addDialogClose(){
        this.$refs.addRef.resetFields()
    },
    // 点击添加参数表单确认按钮调用 发送请求
    addParams(){
        this.$refs.addRef.validate(async val=>{
            if(!val) return
           const {data:res}=await this.$http.post(`categories/${this.cateID}/attributes`,{attr_name:this.addform.attr_name,
            attr_sel:this.activeName})
            if(res.meta.status!==201) {return this.$message.error('添加失败')}
            this.$message.success('添加参数成功')
            // 关闭添加参数对话框
            this.manyOnlyDialog=false
            // 重新渲染表格
            this.getParamsData()
        })
    },
    // 关闭编辑参数对话框表单重置
    editDialogClose(){
        this.$refs.editRef.resetFields()
    },
    // 点击编辑参数按钮
   async showEditDialog(attr_id){
           const {data:res}= await this.$http.get(`categories/${this.cateID}/attributes/${attr_id}`,{params:{attr_sel:this.activeName}})
           if(res.meta.status!==200) {return this.$message.error('获取id失败')}
           this.editform=res.data
        this.editmanyOnlyDialog=true
    },
    // 点击编辑参数对话框确认按钮调用
    editParams(){
        this.$refs.editRef.validate(async val=>{
            if(!val) return
          const {data:res}= await this.$http.put(`categories/${this.cateID}/attributes/${this.editform.attr_id}`,{attr_name:this.editform.attr_name,attr_sel:this.activeName})
          if(res.meta.status!==200){return this.$message.error('编辑参数失败')}
          this.$message.success('编辑参数成功')
           // 关闭编辑参数对话框
            this.editmanyOnlyDialog=false
            // 重新渲染表格
            this.getParamsData()
        })
    },
    // 删除参数
   async removeParams(attrid){
       const confirmResult= await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)

    if(confirmResult!=='confirm'){return this.$message.error('已取消删除')}

    const {data:res}=await this.$http.delete(`categories/${this.cateID}/attributes/${attrid}`)
    if(res.meta.status!==200) {return this.$message.error('删除参数失败')}
    this.$message.success('删除参数成功')
        // 重新渲染表格
    this.getParamsData()
    },
    // 点击+ New Tag 切换输入框
    showInput(row){
        console.log(row);
        row.inputVisible = true
        // this.$nextTick(_ => {
        //   this.$refs.saveTagInput.$refs.input.focus();
        // });
    },

    async handleInputConfirm(row){
        // 判断输入框字符 为0则失去焦点转换为标签
       if(row.inputValue.trim().length===0){
           row.inputValue=''
           row.inputVisible = false
       }

    //    不为0 则
        row.attr_vals.push(row.inputValue.trim())
        row.inputValue=''
        row.inputVisible = false
        this.saveAttrVals(row)
  },
  async saveAttrVals(row){
         const {data:res}=await tihs.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{attr_name:row.attr_name,attr_sel: row.attr_sel,
          attr_vals: row.attr_vals.join(' ')})
           if (res.meta.status !== 200) {
        return this.$message.error('修改参数项失败！')
      }

      this.$message.success('修改参数项成功！')
     },
     handleClose(i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    }
   },
//    计算属性
   computed:{
       isButDisplay(){
           if(this.selectedIdArr.length!==3){
               return true
           }
            return false
       },
    //    获取选中分类的ID
       cateID(){
           if(this.selectedIdArr.length===3){
               return this.selectedIdArr[2]
           }
           return null
       },
    //    判断点击的哪个TAB栏来定义对话框标题
       titleText(){
           if(this.activeName==='many'){
               return '动态参数'
           }else{
               return '静态属性'
           }
       }
   }
}
</script>
<style lang="less" scoped>
.selectGoods {
    margin-top: 15px;
}
.el-cascader{
    width: 250px;
    margin-left: 15px;
}
.el-tag {
    margin: 10px;
}
.input-new-tag {
    width: 120px;
}
</style>